package com.daisy.tools;

import com.daisy.entity.MenuEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version: V1.0
 * @author: daisy
 * @className: MenuTool
 * @packageName: com.daisy.tools
 * @description: 菜单树构建工具
 * @data: 2020-06-14 21:52
 **/
public class MenuTool {

    private List<MenuEntity> menuList;

    public MenuTool(List<MenuEntity> menuList) {
        this.menuList = menuList;
    }

    public static final List<MenuEntity> buildMenuTree(List<MenuEntity> menuList, int pid) {
        List<MenuEntity> list = new ArrayList<>();
        menuList.stream() // 将链表转换为流形式
                .filter(d -> Objects.equals(pid, d.getPid())) // 过滤出和pid同级的菜单
                .collect(Collectors.toList()) // 转换成集合
                .forEach(d -> { // lambda 增强 foreach 循环
                    d.setChildren(buildMenuTree(menuList, d.getId())); // 迭代寻找子菜单
                    list.add(d); // 添加到最终的菜单树中
                });
        return list;
    }

}
